package com.audaque.springboot.foshanupload.web.springsecuritycas.handler;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登出处理器
 */
public class CasSecurityContextLogoutHandler implements LogoutHandler {
    protected final Log logger = LogFactory.getLog(this.getClass());
    private boolean invalidateHttpSession = true;
    private boolean clearAuthentication = true;

    public CasSecurityContextLogoutHandler() {
    }

    public void logout(
            HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        Assert.notNull(request, "HttpServletRequest required");
        if (this.invalidateHttpSession) {
            HttpSession session = request.getSession();

                this.logger.debug("Invalidating session: " + session.getId());
                //session失效
                session.invalidate();
                //发布退出登录事件，自己增加，监听此事件处理一些事情
//        LogoutEvent event = new LogoutEvent();
//        event.setSessionId(session.getId());
//        EventPublisherUtil.publish(event);
            }


        if (this.clearAuthentication) {
            SecurityContext context = SecurityContextHolder.getContext();
            context.setAuthentication((Authentication)null);
        }

        SecurityContextHolder.clearContext();
    }

    public boolean isInvalidateHttpSession() {
        return this.invalidateHttpSession;
    }

    public void setInvalidateHttpSession(boolean invalidateHttpSession) {
        this.invalidateHttpSession = invalidateHttpSession;
    }

    public void setClearAuthentication(boolean clearAuthentication) {
        this.clearAuthentication = clearAuthentication;
    }
}

